//
//  PublicTool.m
//  BSOrange
//
//  Created by kenshin on 14-9-1.
//  Copyright (c) 2014年 BazzarEntertainment. All rights reserved.
//

@import AVKit;
@import AVFoundation;
@import MediaPlayer;

#import "PublicTool.h"
#import "MBProgressHUD.h"
#include <sys/xattr.h>
#import "RKDropdownAlert.h"


#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonHMAC.h>

@implementation PublicTool
{
    //反复init NSDateFormatter开销太大，故重用之
    NSDateFormatter *_dateFormatterYMD;
    NSDateFormatter *_dateFormatterYMD_CH;
    NSDateFormatter *_dateFormatterYMDHMS;
}


static PublicTool *gSharedInstance = nil;

+(PublicTool *)sharedInstance
{
    static dispatch_once_t disonce;
    dispatch_once(&disonce, ^{
        gSharedInstance = [[PublicTool alloc] init];
    });
    
    return gSharedInstance;
}

+ (NSInteger) unicodeLengthOfString: (NSString *) text {
    NSInteger asciiLength = 0;
    
    for (NSUInteger i = 0; i < text.length; i++) {
        
        
        unichar uc = [text characterAtIndex: i];
        
        asciiLength += isascii(uc) ? 1 : 2;
    }
    
    NSInteger unicodeLength = asciiLength / 2;
    
    if(asciiLength % 2) {
        unicodeLength++;
    }
    
    return unicodeLength;
}


//展示HUD提示框（只展示文字,几秒后消失）
+ (void)showHudAlertWithTitle:(NSString *)title inView:(UIView *)tmpView andShowTime:(float)time
{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:tmpView];
    [tmpView addSubview:hud];
    
    UILabel *mainTitle = [[UILabel alloc] initWithFrame:CGRectZero];
    mainTitle.backgroundColor = [UIColor clearColor];
    mainTitle.font = [UIFont fontWithName:defaultFontName size:13];
    mainTitle.textColor = [UIColor whiteColor];
    mainTitle.text = title;
    
    [mainTitle sizeToFit];
    hud.customView = mainTitle;
    
    // Set custom view mode
    hud.mode = MBProgressHUDModeCustomView;
    
    [hud show:YES];
    [hud hide:YES afterDelay:time];
}


//展示HUD加载等待框


//展示HUD加载等待框

+ (MBProgressHUD *)showWaitHudWithTitleInWindow:(NSString *)title
{
    return [PublicTool showWaitHudWithTitle:title inView:[[[UIApplication sharedApplication] windows] lastObject]];
}

+ (MBProgressHUD *)showWaitHudWithTitle:(NSString *)title inView:(UIView *)tmpView
{
    
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:tmpView];
    [tmpView addSubview:hud];
    
    UILabel *mainTitle = [[UILabel alloc] initWithFrame:CGRectZero];
    mainTitle.backgroundColor = [UIColor clearColor];
    mainTitle.font = [UIFont fontWithName:defaultFontName size:15];
    mainTitle.textColor = [UIColor whiteColor];
    mainTitle.text = title;
    
    [mainTitle sizeToFit];
    hud.customView = mainTitle;
    
    // Set custom view mode
    hud.mode = MBProgressHUDModeCustomView;
    
    [hud show:YES];
    
    return hud;
}

+ (void)showNetWorkErrorInView:(UIView *)view
{
    [PublicTool showHudAlertWithTitle:kMsgErrorNetWork inView:view andShowTime:.7];
}

+ (void)showMsg:(NSString *)msg
{
    NSLog(@"windows:%@",[[UIApplication sharedApplication] windows]);
    [PublicTool showHudAlertWithTitle:msg inView:[[[UIApplication sharedApplication] windows] lastObject] andShowTime:.7];
}

+ (void)showTitle:(NSString *)title msg:(NSString *)msg
{
    [PublicTool showTitle:title msg:msg offsetY:0];
}

+ (void)showTitle:(NSString *)title msg:(NSString *)msg offsetY:(CGFloat)offsetY
{
    if (!title && [msg length] > 0) {
        title = msg;
        msg = nil;
    }
    
    UIImage *iconImage = [UIImage imageNamed:@"tipmsgicon"];
//    [RKDropdownAlert title:title message:msg iconImage:iconImage backgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"tipmsgbg"]] textColor:[UIColor whiteColor] time:1.2 offsetY:offsetY];
}

+ (void)showError:(NSString *)title msg:(NSString *)msg offsetY:(CGFloat)offsetY
{
    if (!title && [msg length] > 0) {
        title = msg;
        msg = nil;
    }
    
    if ([title length] > 0 && [msg length] > 0) {
        title = msg;
        msg = nil;
    }
    
    UIImage *iconImage = [UIImage imageNamed:@"tipmsgicon-err"];
//    [RKDropdownAlert title:title message:msg iconImage:iconImage backgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"tipmsgbg-err"]] textColor:[UIColor colorWithRGB:0x6a461e] time:1.2 offsetY:offsetY];
}

+ (void)showError:(NSString *)title msg:(NSString *)msg
{
    [PublicTool showError:title msg:msg offsetY:0];
}

#pragma mark - 时间处理

+ (NSString *)getNowTimeStamp
{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    
    return (timeString);
}

- (NSDateFormatter *)dateFormatterYMD {
    if (! _dateFormatterYMD) {
        _dateFormatterYMD = [[NSDateFormatter alloc] init];
        [_dateFormatterYMD setTimeZone:[NSTimeZone localTimeZone]];
        [_dateFormatterYMD setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatterYMD;
}

- (NSDateFormatter *)dateFormatterYMD_CH {
    if (! _dateFormatterYMD_CH) {
        _dateFormatterYMD_CH = [[NSDateFormatter alloc] init];
        [_dateFormatterYMD_CH setTimeZone:[NSTimeZone localTimeZone]];
        [_dateFormatterYMD_CH setDateFormat:@"yyyy年MM月dd日"];
    }
    return _dateFormatterYMD_CH;
}

- (NSDateFormatter *)dateFormatterYMDHMS {
    if (! _dateFormatterYMDHMS) {
        _dateFormatterYMDHMS = [[NSDateFormatter alloc] init];
        [_dateFormatterYMDHMS setTimeZone:[NSTimeZone localTimeZone]];
        [_dateFormatterYMDHMS setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    return _dateFormatterYMDHMS;
}


+(NSString *)currentDateTime{
	NSDate *date = [NSDate date];
	NSString *timeString = [[[PublicTool sharedInstance] dateFormatterYMDHMS] stringFromDate:date];
	return timeString;
}

+(NSString *)dateTimeYMD:(int)seconds{
	NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
	NSString *timeString = [[[PublicTool sharedInstance] dateFormatterYMD] stringFromDate:date];
	return timeString;
}

+(NSString *)dateTimeYMD_CH:(int)seconds{
	NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
	NSString *timeString = [[[PublicTool sharedInstance] dateFormatterYMD_CH] stringFromDate:date];
	return timeString;
}

+(NSString *)dateTimeYMDHMS:(int)seconds{
	NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
	NSString *timeString = [[[PublicTool sharedInstance] dateFormatterYMDHMS] stringFromDate:date];
    return timeString;
}

+(NSDate *)dateFromString:(NSString *)dateString{
	NSDate *date = [[[PublicTool sharedInstance] dateFormatterYMDHMS] dateFromString:dateString];
    return date;
}

#pragma mark - 其他

+ (NSString *)getUniqueString
{
    int randValue = arc4random() % 1000;//0 到 1000的随机数字
    NSString *randStr = [NSString stringWithFormat:@"%@%d",[self getNowTimeStamp],randValue];
    return randStr;
}

+ (void)showFadeAnimation:(UIView *)view
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    animation.fromValue = [NSNumber numberWithFloat:0.0f];
    animation.toValue = [NSNumber numberWithFloat:1.0f];
    animation.duration = 0.5f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    [view.layer addAnimation: animation forKey: @"FadeIn"];
}


+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    const char* filePath = [[URL path] fileSystemRepresentation];
    
    const char* attrName = "com.apple.MobileBackup";
    u_int8_t attrValue = 1;
    
    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    return result == 0;
}


+(CGRect)amplifyFrame:(CGRect)frame times:(CGFloat)times
{
    CGRect tempFrame = CGRectZero;
    CGFloat width = (times-1)*CGRectGetWidth(frame);
    CGFloat height =(times-1)*CGRectGetHeight(frame);
    tempFrame.origin.x = CGRectGetMinX(frame)-width/2.f;
    tempFrame.origin.y = CGRectGetMinX(frame)-height/2.f;
    tempFrame.size = CGSizeMake(width+CGRectGetWidth(frame), height+CGRectGetHeight(frame));
    return tempFrame;
}

// label设置最小字体大小
+ (void)label:(UILabel *)label setMiniFontSize:(CGFloat)fMiniSize forNumberOfLines:(NSInteger)iLines
{
    if (label)
    {
        label.adjustsFontSizeToFitWidth = YES;
        label.minimumScaleFactor = fMiniSize/label.font.pointSize;
//        if ((iLines != 1) && (IOSVersion < 7.0f))
//        {
//            label.adjustsLetterSpacingToFitWidth = YES;
//        }else{}
    }else{}
}


// 清除PerformRequests和notification
+ (void)cancelPerformRequestAndNotification:(UIViewController *)viewCtrl
{
    if (viewCtrl)
    {
        [[viewCtrl class] cancelPreviousPerformRequestsWithTarget:viewCtrl];
        [[NSNotificationCenter defaultCenter] removeObserver:viewCtrl];
    }else{}
}

+ (UIImage *)roundImage:(UIImage *)image bounds:(CGRect)bounds
{
    UIGraphicsBeginImageContextWithOptions(bounds.size, NO, [[UIScreen mainScreen] scale]);

    [[UIBezierPath bezierPathWithRoundedRect:bounds
                                cornerRadius:bounds.size.width/2] addClip];
    [image drawInRect:bounds];
    
    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return finalImage;
}
+ (void)roundImage:(UIImage *)image bounds:(CGRect)bounds block:(void (^)(UIImage *))block
{
    //CGRect bounds = strongSelf->_headImageLayer.bounds;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *finalImage = nil;
        UIGraphicsBeginImageContextWithOptions(bounds.size, NO, [[UIScreen mainScreen] scale]);
        [[UIBezierPath bezierPathWithRoundedRect:bounds
                                    cornerRadius:bounds.size.width/2] addClip];
        [image drawInRect:bounds];
        finalImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        if (finalImage) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (block) {
                    block(finalImage);
                }
            });
        }
    });
}

+ (NSCalendar *)currentCalendar {
    if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
        return [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    }
    return [NSCalendar currentCalendar];
}

+ (NSString *)relativeDateStringForTimeinterval:(long long)timeinterval
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeinterval];
    return [self relativeDateStringForDate:date];
}

+ (NSString *)relativeDateStringForDate:(NSDate *)date
{
    NSCalendarUnit units = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour |NSCalendarUnitMinute;
    
    NSDateComponents *compsNow = [[self currentCalendar] components:units fromDate:[NSDate date]];
    NSDateComponents *comps = [[self currentCalendar] components:units fromDate:date];
    NSString *year = FMT(@"%ld", comps.year);
    NSString *month = FMT(@"%02ld", comps.month);
    NSString *day = FMT(@"%02ld", comps.day);
    NSString *hour = FMT(@"%02ld", comps.hour);
    NSString *min = FMT(@"%02ld", comps.minute);
    
    NSDateComponents *compsDiff = [[NSDateComponents alloc] init];
    compsDiff.year = compsNow.year - comps.year;
    compsDiff.month = compsNow.month - comps.month;
    compsDiff.day = compsNow.day - comps.day;
    compsDiff.hour = compsNow.hour - comps.hour;
    compsDiff.minute = compsNow.minute - comps.minute;
    
    NSString *dateStr = nil;
    if (compsDiff.year == 0 && compsDiff.month == 0 && compsDiff.day >= 0) {
        // 同年同月
        if (compsDiff.day == 2) {
            dateStr = FMT(@"前天 %@:%@", hour, min);
        } else if (compsDiff.day == 1) {
            dateStr = FMT(@"昨天 %@:%@", hour, min);
        } else if (compsDiff.day == 0) {
            dateStr = FMT(@"%@:%@", hour, min);
        } else if (compsDiff.day > 2) {
            dateStr = FMT(@"%@月%@日 %@:%@", month, day, hour, min);
        }
    } else if (compsDiff.year == 0 && (compsDiff.month > 0 || compsDiff.day > 0)) {
        // 同年
        dateStr = FMT(@"%@月%@日 %@:%@", month, day, hour, min);
    } else {
        // 不同年
        dateStr = FMT(@"%@年%@月%@日 %@:%@", year, month, day, hour, min);
    }
    return dateStr;
}

+ (NSString *)md5StringForString:(NSString *)string {
    const char *str = [string UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (uint32_t)strlen(str), r);
    return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
}

+ (NSString*)md5StringForData:(NSData *)data
{
    unsigned char result[16];
    CC_MD5( data.bytes, data.length, result ); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];  
}


+ (void)showVideoPlayer:(NSString *)videoURLString {
    if (mIsIOS9) {
        AVPlayer *player = [AVPlayer playerWithURL:[NSURL URLWithString:videoURLString]];
        AVPlayerViewController *playerViewController = [AVPlayerViewController new];
        playerViewController.player = player;
        [[KSNavi defaultNavi] presentViewController:playerViewController animated:YES completion:nil];
        [playerViewController.player play];
    } else {
        MPMoviePlayerViewController  * moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:videoURLString]];
        [[KSNavi defaultNavi] presentMoviePlayerViewControllerAnimated:moviePlayerController];
        moviePlayerController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    }
}

#pragma mark IDPhotoBrowser


+ (void)showPhotoGallaryWithPhotos:(NSArray<IDMPhoto *> *)photos startAtIndex:(NSInteger)currentIndex animatedFromView:(UIView *)animatedFromView animatedImage:(UIImage *)animatedImage {
    
    IDMPhotoBrowser *browser = [[IDMPhotoBrowser alloc] initWithPhotos:photos animatedFromView:animatedFromView];
    browser.forceHideStatusBar = NO;
    browser.disableHideControls = YES;
    browser.displaySaveButton = YES;
    browser.displayToolbar = NO;
    browser.useBottomOptionView = YES;
    //    browser.delegate = self;
    browser.usePopAnimation = YES;
    browser.scaleImage = animatedImage;
    [browser setInitialPageIndex:currentIndex];
    [[[KSNavi defaultNavi] topViewController] presentViewController:browser animated:YES completion:nil];
}

+ (void)showPhotoGallaryWithPhotoURLs:(NSArray *)photoURLs startAtURL:(NSString*)currentPhotoURL animatedFromView:(UIView *)animatedFromView animatedImage:(UIImage *)animatedImage
{
    NSMutableArray<IDMPhoto *>* photos = [NSMutableArray array];
    NSInteger currentIndex;
    if(photoURLs.count > 0){
        for (NSString* photoURL in photoURLs) {
            IDMPhoto *photo = [IDMPhoto photoWithURL:[NSURL URLWithString:photoURL]];
            [photos addObject:photo];
        }
        currentIndex = [photoURLs indexOfObject:currentPhotoURL];
    }else{
        IDMPhoto* photo = [IDMPhoto photoWithURL:[NSURL URLWithString:currentPhotoURL]];
        [photos addObject:photo];
        currentIndex = 0;
    }
    
    [self showPhotoGallaryWithPhotos:photos startAtIndex:currentIndex animatedFromView:animatedFromView animatedImage:animatedImage];
}


+ (void)showPhotoGallaryWithPhotoFilePaths:(NSArray *)filePaths startAtFilePath:(NSString*)currentFilePath animatedFromView:(UIView *)animatedFromView animatedImage:(UIImage *)animatedImage {
    NSMutableArray<IDMPhoto *>* photos = [NSMutableArray array];
    NSInteger currentIndex = 0;
    if(filePaths.count > 0){
        for (NSString* photoPath in filePaths) {
            IDMPhoto *photo = [IDMPhoto photoWithFilePath:photoPath];
            [photos addObject:photo];
        }
        currentIndex = [filePaths indexOfObject:currentFilePath];
    }else{
        IDMPhoto* photo = [IDMPhoto photoWithFilePath:currentFilePath];
        [photos addObject:photo];
        currentIndex = 0;
    }
    
    [self showPhotoGallaryWithPhotos:photos startAtIndex:currentIndex animatedFromView:animatedFromView animatedImage:animatedImage];
}


@end
